const jwtUtil =require('../utils/jwtUtils')
const redisUtil=require('../utils/redisUtils')
global.globalKey='123456'
module.exports=class user_dao extends require('../model/users_mod') {
  static async Login(req, res) {
    let body = req.body
    let LoginData = await this.LoginUser(body.id, body.password, body.type)
    if (LoginData.length != 0) {
      let jwt_token = jwtUtil.sign({
        id: LoginData[0].id,
        username: LoginData[0].username,
        head: LoginData[0].head,
        type: LoginData[0].type,
        classes:LoginData[0].classes
      }, global.globalKey, 3600)
      res.send({LoginData, jwt_token})
    } else {
      res.status(500).send(500)
    }
  }

  static async getUserDataByToken(req,res) {
    console.log(req.query)
    let result = await jwtUtil.verifysync(req.query.token,global.globalKey)
    res.send(result)
  }

  static async getUsersByTypePage(req,res){
    console.log(req.query)
    let query=req.query;
    let data=await this.getUsersByTypePageMod(query.type,query.currPage,query.pageNum)
    let total=await this.getUserByTypePageTotal(query.type)
    res.send({data,total:total[0].count})
  }

  static async delUserData(req,res){
    let result= await this.delUserDataMod(req.query.id)
    // result+= await this.delReadMod(req.query.id)
    res.send(result)
  }

  static async upDataUser(req,res){
    let body =req.body
    let u_id=body.u_id
    let username=body.username
    let sex =body.sex
    let address =body.address
    let type=body.type
    let classes=body.classes
    let result= await this.upDataUserMod(u_id,username,sex,address,type,classes)
    res.send(result)
  }

  /**
   * 将redis数据存入数据库
   * @param req
   * @param res
   * @returns {Promise<void>}
   */
  static async setXlsxData(req,res){
    let xlsxData=await redisUtil.get("xmldata",'0')
    let AllUser=await this.getAllUser();

    xlsxData=JSON.parse(xlsxData)[0].data
    console.log(xlsxData)
    let inXlsxArr=[];

    for (let i=1;i<xlsxData.length;i++){
      let falg=true;
      let xlsxObj={};
      xlsxObj.id=xlsxData[i][0]
      xlsxObj.username=xlsxData[i][1]
      xlsxObj.password=xlsxData[i][2]
      xlsxObj.head=xlsxData[i][3]
      xlsxObj.address=xlsxData[i][4]
      xlsxObj.sex=xlsxData[i][5]
      xlsxObj.classes=xlsxData[i][6]
      xlsxObj.type=xlsxData[i][7]

      for (let j=0;j<AllUser.length;j++){
        if(xlsxObj.id==AllUser[j].id) falg=false
      }
      if(falg) inXlsxArr.push(xlsxObj)
    }
    this.inXlsxData(inXlsxArr)
  }


  /**
   * 修改个人用户密码
   * @param req
   * @param res
   * @returns {Promise<void>}
   */
  static async upPassword(req,res){
    let verify=await jwtUtil.verifysync(req.body.token,globalKey)
    let u_id=verify.id
    let oldPassword=req.body.oldPassword
    let newPassword=req.body.newPassword
    let result=await this.upPasswordMod(u_id,oldPassword,newPassword)

    if(result.changedRows==0)
      res.send('修改失败,可能是新密码与旧密码一致')
    else
      res.send('修改密码成功')
  }
}
